package com.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 这种方案缺陷，就是很难
 */
public class JUC_CountDownLatch_taobao_interview_21 {
    volatile List<Object> list = new ArrayList<>();


    void add(Object o){
        list.add(o);
    }
    int size(){
        return list.size();
    }

    public static void main(String[] args) {
        final Object lock = new Object();

        JUC_CountDownLatch_taobao_interview_21 t = new JUC_CountDownLatch_taobao_interview_21();
        CountDownLatch c = new CountDownLatch(1);

        Thread t1 = new Thread(() -> {
                System.out.println("t1 启动" );

                if(t.size() != 5){
                    try {
                        c.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println("t1 end");
        }, "t1");

        Thread t2 = new Thread(() -> {
                for(int i=0;i<10;i++){

                    t.add(new Object());
                    System.out.println("add "+i);

                    if(t.size() == 5){
                        c.countDown();

                        try {
                            c.await();// 这里继续使用await 用上这个门好像不行
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                    /*
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }*/
                }
        }, "t2");

        t1.start();
        t2.start();
    }
}
